package com.ohuang.test_compose.composeView.webview

import android.annotation.SuppressLint
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ProgressBar
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import com.ohuang.test_compose.util.SizeUtils

/**
 * WebView for compose
 */
@SuppressLint("UseCompatLoadingForDrawables")
@Composable
fun WebViewPage(
    url: String
) {
    var ctrl: WebViewCtrl? by remember { mutableStateOf(null) }
    Box {
        var isRefreshing: Boolean by remember { mutableStateOf(false) }


        AndroidView(
            modifier = Modifier
                .fillMaxSize(),
            factory = { context ->
                FrameLayout(context).apply {
                    layoutParams = FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT
                    )

                    val webView = WebView(context).apply {
                        layoutParams = ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
                        )
                    }

                    val progressView = ProgressBar(context).apply {
                        layoutParams = ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            SizeUtils.dp2px(50f)
                        )


                    }


                    webView.setOnKeyListener(object : View.OnKeyListener {
                        override fun onKey(p0: View?, p1: Int, p2: KeyEvent?): Boolean {
                            if (p1 == KeyEvent.KEYCODE_BACK) {
                                 if (webView.canGoBack()) {
                                    webView.goBack()
                                     return   true
                                }
                            }
                            return false
                        }
                    })

                    addView(webView)
                    addView(progressView)
                    ctrl = WebViewCtrl(this, url, onWebCall = { isFinish ->
                        isRefreshing = !isFinish
                    })
                    ctrl?.initSettings()
                }

            },
            update = {

            }
        )

    }
}